package com.example.fechat.activity

import android.net.Uri
import android.os.Bundle
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.FileUtils
import com.example.fechat.R
import com.example.fechat.adapter.ChatAdapter
import com.example.fechat.bean.MessageBean
import com.example.fechat.room.user.UserDBUtils
import com.example.fechat.room.user.UserEntity
import com.example.fechat.utils.CSVUtils
import com.example.fechat.utils.Files
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar


class MessageActivity : AppCompatActivity() {
    private val beans = ArrayList<MessageBean>()
    private var adapter: ChatAdapter? = null
    private lateinit var itemView: RecyclerView
    private lateinit var userEntity: UserEntity
    private var messagePath = ""
    private val userName = "Admin"
    private val imageUris = ArrayList<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ImmersionBar.with(this).statusBarDarkFont(true).statusBarColor(R.color.title)
            .navigationBarColor(R.color.white).navigationBarDarkIcon(true).init()
        setContentView(R.layout.activity_message)
        Files.initPicker(this, 9, pickFileResultListener)

        val backTv = findViewById<TextView>(R.id.backTv)
        val inputText: EditText = findViewById(R.id.inputText)
        val sendText: TextView = findViewById(R.id.sendText)
        val mediaTv: ImageView = findViewById(R.id.mediaTv)
        val userName: TextView = findViewById(R.id.userName)
        backTv.setOnClickListener {
            finish()
        }
        sendText.setOnClickListener {
            sendText(inputText.text.toString())
            inputText.setText("")
            itemView.smoothScrollToPosition(beans.size - 1)
        }
        mediaTv.setOnClickListener {
            Files.pickMedia(Files.PICK_IMAGE_VIDEO)
        }
        getBundle()
        initItemRecyclerView()
        userName.text = userEntity.userName
    }

    private val pickFileResultListener = object : Files.PickFileResultListener {
        override fun onPick(uris: List<String>) {
            runOnUiThread {
                uris.forEach {
                    insertMessage(it, "image:*")
                    Files.Uri2Path(this@MessageActivity, Uri.parse(it))?.let { it1 -> imageUris.add(it1) }
                }
                adapter?.setNewData()
                itemView.smoothScrollToPosition(beans.size - 1)
            }
        }
    }

    private fun getBundle() {
        val userInfo = intent.getStringExtra("UserInfo")
        userEntity = Gson().fromJson(userInfo, UserEntity::class.java)
        messagePath = CSVUtils.getPath(this, userEntity.userId)
        FileUtils.createOrExistsFile(messagePath)
    }

    override fun onResume() {
        super.onResume()
        beans.clear()
        imageUris.clear()
        beans.addAll(CSVUtils.readFromCSV(messagePath))
        if (beans.size > 0) {
            itemView.smoothScrollToPosition(beans.size - 1)
        }
        beans.forEach {
            if (it.message.contains("content://")) {
                Files.Uri2Path(this, Uri.parse(it.message))?.let { it1 -> imageUris.add(it1) }
            }
        }
    }

    private fun initItemRecyclerView() {
        itemView = findViewById(R.id.itemView)
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
        itemView.layoutManager = layoutManager
        adapter = ChatAdapter(this, beans, imageUris, userEntity)
        itemView.adapter = adapter
    }

    private fun sendText(message: String) {
        insertMessage(message, "text:*")
        adapter?.setNewData()
    }

    private fun insertMessage(message: String, messageType: String) {
        val messageBean = MessageBean(
            message, userName, false, System.currentTimeMillis(), true, messageType
        )
        beans.add(messageBean)
        CSVUtils.writeToCSV(messageBean, messagePath)
        val messageBeanResp =
            MessageBean(
                message,
                userEntity.userName,
                true,
                System.currentTimeMillis(),
                true,
                messageType
            )
        beans.add(messageBeanResp)
        CSVUtils.writeToCSV(messageBeanResp, messagePath)

        userEntity.duration = System.currentTimeMillis()
        userEntity.last_message = message
        UserDBUtils.insertUser(this, userEntity)
    }
}